package com.dmall.chapter04.section11;

import com.dmall.chapter02.section09.Graph;

/**
 * 检测一张图是否是二分图
 * @author wx
 * @date 2020-02-25 22:48:09
 */
public class BiPartitionDetection {

    private Graph G;
    private boolean[] visited;
    private int[] colors;
    private boolean isBiPartite = true;

    public BiPartitionDetection(Graph G) {
        this.G = G;
        this.visited = new boolean[G.V()];
        this.colors = new int[G.V()];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = -1;
        }
        for (int v = 0; v < G.V(); v++) {
            if (!visited[v]) {
                if (!dfs(v, 0)) {
                    isBiPartite = false;
                    break;
                }
            }
        }
    }

    private boolean dfs(int v, int color) {
        visited[v] = true;
        colors[v] = color;
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                if (!dfs(w, 1 - color)) {
                    return false;
                }
            } else if (colors[v] == colors[w]) {
                return false;
            }
        }
        return true;
    }

    public boolean isBiPartite() {
        return isBiPartite;
    }

    public static void main(String[] args) {
        String filename = BiPartitionDetection.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        BiPartitionDetection biPartitionDetection = new BiPartitionDetection(g);
        System.out.println(biPartitionDetection.isBiPartite());

        String filename2 = BiPartitionDetection.class.getClassLoader().getResource("g3.txt").getPath();
        Graph g2 = new Graph(filename2);
        BiPartitionDetection biPartitionDetection2 = new BiPartitionDetection(g2);
        System.out.println(biPartitionDetection2.isBiPartite());
    }
}
